<cfmodule template="../../tag/layout.cfm">
<script type="text/javascript" src="assets/plupload/js/plupload.full.min.js"></script>
<cfscript>
	if( structKeyExists(rc, "ids") && listlen(ids) > 0){
		checkedids = rc.ids;
	}else{
		checkedids = 0;
	}
</cfscript>
<table id="grid"></table>
<div id="toolbar" style="display: none;">
	<form id="searchForm">
		<table>
			<tr>

				<td>文件名称</td>
				<td><input name="clientname" style="width: 80px;" /></td>
				<td>创建时间</td>
				<td>
					<input name="created_ge"  class="easyui-datebox" style="width:100px"/>
					-
					<input name="created_le"  class="easyui-datebox" style="width:100px"/>
				</td>
				<td>
					<a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:'ext-icon-zoom',plain:true" onclick="grid.datagrid('load',fw.serializeObject($('#searchForm')));">过滤</a>
					<a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:'ext-icon-zoom_out',plain:true" onclick="$('#searchForm input').val('');grid.datagrid('load',{});">重置过滤</a>
				</td>
			</tr>
		</table>
	</form>
	<table align="center">
		<tr>
			<td>
				<div id="uploader" class="uploader" style="height:50px;">
					<a id="selectFiles" href="##">
						<span class="label">
							请选择一个或多个文件
						</span>
						<span class="standby">
							等待文件上传中...
						</span>
						<span class="progress">
							正在上传文件，完成进度 - <span class="percent"></span>%
						</span>
					</a>
				</div>
			</td>
		</tr>
	</table>
</div>

</cfmodule>
<script type="text/javascript">
	var closeDialog = function($dialog) {
		$dialog.dialog('destroy');
	}

	var submitForm = function($dialog, $btn)  {
		var ids = [];
		var rows = $('#grid').datagrid('getSelections');
		var options = "<option>选择文件 ( 选中了 "+ rows.length +" 个 )</option>";
		for(var i=0; i<rows.length; i++){
			ids.push(rows[i].id);
			options +="<option>" + rows[i].clientname + "</option>";
		}

		$btn.next('.selectFilesValue').val(ids.join(','));
		$btn.prev('.selectFiles').html(options);

		if($btn.next('.selectFilesValue').attr('click')!='undefined'){
			$btn.next('.selectFilesValue').click();
		}

		$dialog.dialog('destroy');
	};

	var clearSelectedFiles = function($dialog, $btn)  {
		var loadData=[];
		$btn.next('.selectFilesValue').val('');
		$btn.prev('.selectFiles').html('<option>选择文件</option>');

		if($btn.next('.selectFilesValue').attr('click')!='undefined'){
			$btn.next('.selectFilesValue').click();
		}

		$dialog.dialog('destroy');
	};

	(function( $, plupload ) {

		// Find and cache the DOM elements we'll be using.
		var dom = {
			uploader: $( "#uploader" ),
			percent: $( "#uploader span.percent" )
		};


		// Instantiate the Plupload uploader.
		var uploader = new plupload.Uploader({

			// Try to load the HTML5 engine and then, if that's not supported, the Flash
			// fallback engine.
			// --
			// NOTE: I had read that Chunking was not available in the Flash runtime; however,
			// after forcing the Flash runtime, it seems that chunking IS available, but is
			// significantly slower than it is in the html5 runtime.
			runtimes: "html5,flash",

			// The upload URL - this is where chunks OR full files will go.
			url: "?action=uploader.uploaderFiles",

			// The ID of the drop-zone element.
			drop_element: "uploader",

			// To enable click-to-select-files, you can provide a browse button. We can
			// use the same one as the drop zone.
			browse_button: "selectFiles",

			// For the Flash engine, we have to define the ID of the node into which
			// Pluploader will inject the <OBJECT> tag for the flash movie.
			container: "uploader",

			// The URL for the SWF file for the Flash upload runtime for browsers that
			// don't support HTML5.
			flash_swf_url: "assets/plupload/js/Moxie.swf",

			// Needed for the Flash environment to work.
			urlstream_upload: true,

			// The name of the form-field that will hold the upload data.
			file_data_name: "file",

			// Send any additional params (ie, multipart_params) in multipart message
			// format.
			multipart: true,

			filters : [
	            {title : "Image files", extensions : "jpg,gif,png,ppt"},
	            {title : "Excel files", extensions : "xls"},
	            {title : "Zip files", extensions : "zip,avi"}
	        ],

			views: {
	            list: true,
	            thumbs: true, // Show thumbs
	            active: 'thumbs'
	        },

			max_file_size : '2mb',

			// This defines the maximum size that each file chunk can be.
			// --
			// NOTE: I'm setting it particularly low for the demo. In general, you don't
			// want it to be too small because the chunking has a performance hit. Chunking
			// is meant for fault-tolerance and browser limitations.
			chunk_size: "100kb",

			// If the upload of a chunk fails, this is the number of times the chunk
			// should be re-uploaded before the upload (overall) is considered a failure.
			max_retries: 3

		});


		// Set up the event handlers for the uploader.
		uploader.bind( "Init", handlePluploadInit );
		uploader.bind( "Error", handlePluploadError );
		uploader.bind( "FilesAdded", handlePluploadFilesAdded );
		uploader.bind( "QueueChanged", handlePluploadQueueChanged );
		uploader.bind( "BeforeUpload", handlePluploadBeforeUpload );
		uploader.bind( "UploadProgress", handlePluploadUploadProgress );
		uploader.bind( "ChunkUploaded", handlePluploadChunkUploaded );
		uploader.bind( "FileUploaded", handlePluploadFileUploaded );
		uploader.bind( "StateChanged", handlePluploadStateChanged );

		// Initialize the uploader (it is only after the initialization is complete that
		// we will know which runtime load: html5 vs. Flash).
		uploader.init();


		// ------------------------------------------ //
		// ------------------------------------------ //


		// I provide access to the uploader and the file right before the upload is about
		// to being. This allows for just-in-time altering of the settings.
		function handlePluploadBeforeUpload( uploader, file ) {

			console.log( "Upload about to start.", file.name );

		}


		// I handle the successful upload of one of the chunks (of a larger file).
		function handlePluploadChunkUploaded( uploader, file, info ) {

			console.log( "Chunk uploaded.", info.offset, "of", info.total, "bytes." );

		}


		// I handle any errors raised during uploads.
		function handlePluploadError() {
			alert("Error during upload.");
			console.warn( "Error during upload." );

		}


		// I handle the files-added event. This is different that the queue-changed event.
		// At this point, we have an opportunity to reject files from the queue.
		function handlePluploadFilesAdded( uploader, files ) {

			console.log( "Files selected." );
			// Example: file.splice( 0, 1 ).

		}


		// I handle the successful upload of a whole file. Even if a file is chunked,
		// this handler will be called with the same response provided to the last
		// chunk success handler.
		function handlePluploadFileUploaded( uploader, file, response ) {
			//alert(response.response);
			console.log( "Entire file uploaded.", response );

		}


		// I handle the init event. At this point, we will know which runtime has loaded,
		// and whether or not drag-drop functionality is supported.
		function handlePluploadInit( uploader, params ) {

			console.log( "Initialization complete." );
			console.info( "Drag-drop supported:", !! uploader.features.dragdrop );

		}


		// I handle the queue changed event.
		function handlePluploadQueueChanged( uploader ) {

			console.log( "Files added to queue." );

			if ( uploader.files.length && isNotUploading() ){

				uploader.start();

			}

		}


		// I handle the change in state of the uploader.
		function handlePluploadStateChanged( uploader ) {

			if ( isUploading() ) {

				dom.uploader.addClass( "uploading" );

			} else {

				dom.uploader.removeClass( "uploading" );

			}

		}


		// I handle the upload progress event. This gives us the progress of the given
		// file, NOT of the entire upload queue.
		function handlePluploadUploadProgress( uploader, file ) {

			console.info( "Upload progress:", file.percent );

			dom.percent.text( file.percent );

		}


		// I determine if the upload is currently inactive.
		function isNotUploading() {

			var currentState = uploader.state;

			return( currentState === plupload.STOPPED );

		}


		// I determine if the uploader is currently uploading a file (or if it is inactive).
		function isUploading() {

			var currentState = uploader.state;

			return( currentState === plupload.STARTED );

		}

	})( jQuery, plupload );


	$(function(){
		//列表操作
		var gird;
		grid = $('#grid').datagrid({
			fit: true,
			border:false,
			collapsible:false,
			pagination:true,
			singleSelect:false,
			rownumbers:true,
			sortName:'id',
			idField:'id',
			sortOrder:'desc',
			toolbar : '#toolbar',
			url:'?action=uploader.list',
			columns:[[
				{field:'ck',checkbox:true},
				{field:'id',title:'ID',width:40,sortable:true},
				{field:'clientname',title:'文件名称',width:220,sortable:true},
				{field:'filesize',title:'文件大小',width:60,align:'center', sortable:true,formatter: function(value, row) {
		                return fw.getFileSize(value);
		        }},
				{field:'filewidth',title:'宽度',width:40,align:'center',sortable:true},
				{field:'fileheight',title:'高度',width:40,align:'center',sortable:true},
				{field:'fileext',title:'类型',width:40,align:'center',sortable:true},
				{field:'created',title:'添加时间',width:80,align:'center',sortable:true},
				{
					title : '操作',
					field : 'action',
					width : '70',
					formatter : function(value, row) {
						var str = '';
							str += fw.formatString('<img class="iconImg ext-icon-note" title="查看" onclick="showFun(\'{0}\');"/>', row.id);
							str += fw.formatString('<img class="iconImg ext-icon-note_delete" title="删除" onclick="removeFun(\'{0}\');"/>', row.id);

						return str;
					}
				}
			]],
			onLoadSuccess : function(data) {
				$('.iconImg').attr('src', fw.pixel_0);
				var checkedids = '<cfoutput>#checkedids#</cfoutput>';
				$.each(data.rows, function(index, item){
					if( $.inArray(item.id.toString(),checkedids.split(',')) != -1){
						 grid.datagrid('checkRow', index);
					}
				});

			}
		});
	});

</script>